package io.bdmc.modules.api.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.bdmc.common.http.HttpAPIService;
import io.bdmc.common.http.HttpResult;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.common.utils.WebTokenUtil;
import io.bdmc.modules.api.annotation.AuthIgnore;
import io.bdmc.modules.bss.entity.SmkAlarm;
import io.bdmc.modules.bss.entity.SmkDevice;
import io.bdmc.modules.bss.entity.SmkShop;
import io.bdmc.modules.bss.model.AlarmParam;
import io.bdmc.modules.bss.model.ShopLocation;
import io.bdmc.modules.bss.model.ShopParam;
import io.bdmc.modules.bss.service.ISmkAlarmService;
import io.bdmc.modules.bss.service.ISmkDeviceService;
import io.bdmc.modules.bss.service.ISmkShopService;
import io.bdmc.modules.sys.entity.SysUser;
import io.bdmc.modules.sys.service.SysUserService;

@RestController
@RequestMapping(value = "/api/admin")
public class AdminController extends BaseApiController {
    @Autowired
    private ISmkShopService _shopSvs;
    @Autowired
    private ISmkDeviceService _devSvs;
    @Autowired
    private ISmkAlarmService _alarmSvs;
    @Autowired
    private SysUserService _userSvs;
    @Autowired
    private HttpAPIService _apiSVs;

    @AuthIgnore
    @PostMapping("test")
    public R register(String mobile, String password){
        logger.info("api info test");
        return R.ok();
    }

    @AuthIgnore
    @PostMapping(value = "/bind")
    public R bind(@RequestBody Map<String, Object> map) {
        if (StringUtils.isEmpty(map.get("loginName")) || StringUtils.isEmpty(map.get("password"))) {
            return R.error(-1, "参数错误");
        }
        String openid = String.valueOf(map.get("openid"));
        String wxImage = String.valueOf(map.get("wxImage"));
        //String wxName = String.valueOf(map.get("wxName"));
        String loginName = String.valueOf(map.get("loginName"));
        String password = String.valueOf(map.get("password"));

        // 用户信息
        SysUser user = _userSvs.queryByUserName(loginName);

        // 账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
            return R.error(-1, "账号或密码不正确");
        }

        user.setWxImage(wxImage);
        user.setWxName(user.getRealname());
        user.setOpenid(openid);
        user.updateById();
        String token = WebTokenUtil.createJWT(user.getUserId(), user.getOpenid(), user.getDeptId(), user.getWxName(),
                36000000);

        Map<String, Object> respMap = new HashMap<>();
        respMap.put("wxName", user.getRealname());
        respMap.put("wxImage", wxImage);
        respMap.put("openid", openid);
        respMap.put("dep_id", user.getDeptId());
        respMap.put("mobile", user.getMobile());
        respMap.put("username", loginName);
        respMap.put("token", token);
        return R.ok().putData(respMap);

    }

    @PostMapping(value = "/unbind")
    public R unbind() {
        String openid = getLoginName();
        SysUser user = _userSvs.queryByOpenid(openid);
        if (user != null) {
            user.setWxImage("");
            user.setWxName("");
            user.setOpenid("");
            Boolean b = user.updateById();
            return R.trueOfFalse(b);
        }
        return R.error(-1, "参数错误");
    }

    // 获取商户信息
    @PostMapping(value = "/shops")
    public R getShops(@RequestBody ShopParam param) {
        Long dep_id = Long.valueOf(request.getAttribute("dep_id").toString());
        param.setDeptId(dep_id);
        MyPage<SmkShop> myPage = new MyPage<SmkShop>(param.getCurrent(), param.getSize());
        MyPage<ShopLocation> pageData = _shopSvs.getByDepId(myPage, param);
        return R.ok().putData(MyMap.ok(pageData.getRecords(), pageData.getTotal()));
    }

    // 根据商户id获取设备信息
    @PostMapping(value = "/devices")
    public R getDevices(@RequestBody Map<String, Object> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        QueryWrapper<SmkDevice> w1 = new QueryWrapper<SmkDevice>();
        w1.eq("shop_id", id);
        List<SmkDevice> devs = _devSvs.list(w1);
        List<Map<Object, Object>> list = new LinkedList<>();
        for (SmkDevice dev : devs) {
            Map<Object, Object> tempmap = new HashMap<>();
            tempmap.put("imei", dev.getImei());
            tempmap.put("devName", dev.getDevName());
            tempmap.put("devModel", dev.getDevModel());
            tempmap.put("devStatus", dev.getDevStatus());
            tempmap.put("installDate", dev.getInstallDate());
            tempmap.put("installAddr", dev.getInstallAddr());
            list.add(tempmap);
        }
        return R.ok().putData(MyMap.ok(list, list.size()));
    }

    // 根据商户id获取设备报警信息
    @PostMapping(value = "/alarm")
    public R getDevicesAlarm(@RequestBody Map<String, String> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        List<SmkAlarm> alarms = _alarmSvs.wxSelectAlarmByShopId(id);
        return R.ok().putData(alarms);
    }

    // 子单位信息
    @PostMapping(value = "/single_shop")
    public R getShopInfo(@RequestBody Map<String, String> map) {
        int id = Integer.valueOf(String.valueOf(map.get("id")));
        SmkShop shop = _shopSvs.getById(id);
        return R.ok().putData(shop);
    }

    // 获取报警信息
    @RequestMapping(value = "/alarmlist")
    public R alarmList(@RequestBody AlarmParam params) {
        Long dep_id = Long.valueOf(request.getAttribute("dep_id").toString());
        params.setDeptId(dep_id);
        MyPage<SmkAlarm> myPage = new MyPage<>(params.getCurrent(), params.getSize());
        MyPage<SmkAlarm> map = _alarmSvs.wxSelectAlarm(myPage, params);
        return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
    }

    @PostMapping(value = "/statistic")
    public R statistic() {
        Long dep_id = Long.valueOf(request.getAttribute("dep_id").toString());
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("devStc", _devSvs.wxDeviceSum(dep_id));
        // results.put("gcbdStc",_gcSvs.findAreaGCBDSum(dep_id));
        results.put("alarmStc", _alarmSvs.wxAlarmSum(dep_id));
        return R.ok().putData(results);
    }

    // 解除报警
    @PostMapping(value = "/relievealarm")
    public R relieveAlarm(@RequestBody Map<String, Object> map) {
        Integer alarmReason = 0;
        if( map.get("alarmReason") != null){
            alarmReason = Integer.valueOf(String.valueOf(map.get("alarmReason")));
        }
        if (map.get("alarmId") == null || map.get("dealMethod") == null || map.get("dealType") == null
                || map.get("dealResult") == null ) {
            return R.error(-1, "参数错误");
        }
        Integer id = Integer.valueOf(String.valueOf(map.get("alarmId")));
        Integer dealMethod = Integer.valueOf(String.valueOf(map.get("dealMethod")));
        Integer dealType = Integer.valueOf(String.valueOf(map.get("dealType")));
        String dealResult = String.valueOf(map.get("dealResult"));

        SmkAlarm alarm = _alarmSvs.getById(id);
        alarm.setDealMethod(dealMethod);
        alarm.setDealType(dealType);
        alarm.setDealResult(dealResult);
        alarm.setAlarmReason(alarmReason);
        alarm.setAlarmStat(2);// 2是已处理
        boolean b = _alarmSvs.updateById(alarm);
        if(alarm.getAlarmType().equals(2)){
            SmkDevice dev = _devSvs.getById(alarm.getDevId());
            try {
                HttpResult re = _apiSVs.doGetCommand(dev.getDevKey(), "5859");
                logger.debug("消音结果："+re.getCode()+"||"+re.getBody());
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        }
        return R.trueOfFalse(b);
    }

}